/**
 * Notes: 智能问答聊天记录模型
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux@qq.com
 * Date: 2023-03-22 07:48:00 
 */

const BaseProjectModel = require('./base_project_model.js');

class ChatModel extends BaseProjectModel {

	constructor() {
		super();

		this.setModel('chat');
	}

	/**
	 * 获取用户聊天记录
	 * @param {*} userId 
	 * @param {*} page 
	 * @param {*} size 
	 * @param {*} oldTotal 
	 */
	async getUserChat(userId, page, size, oldTotal = 0) {
		return await this.getList({
			CHAT_USER_ID: userId
		}, {
			'CHAT_ADD_TIME': 'desc' // 按照添加时间倒序
		}, page, size, oldTotal);
	}

	/**
	 * 添加聊天记录
	 * @param {*} userId 
	 * @param {*} question 
	 * @param {*} answer 
	 * @param {*} references 
	 */
	async addChat(userId, question, answer, references = []) {
		const data = {
			CHAT_USER_ID: userId,
			CHAT_QUESTION: question,
			CHAT_ANSWER: answer,
			CHAT_ADD_TIME: this._timestamp(), // 添加时间
		};

		// 如果有参考文献
		if (references && references.length > 0) {
			data.CHAT_REF_KNOWLEDGE_IDS = references.map(ref => ref.id).join(',');
			data.CHAT_REF_KNOWLEDGE_TITLES = references.map(ref => ref.title).join(',');
			data.CHAT_REF_KNOWLEDGE_SCORES = references.map(ref => ref.score).join(',');
		}

		return await this.insert(data);
	}

	/**
	 * 获取聊天记录详情
	 * @param {*} id 
	 */
	async getChat(id) {
		return await this.getOne(id);
	}

	/**
	 * 删除聊天记录
	 * @param {*} id 
	 */
	async delChat(id) {
		return await this.del(id);
	}
}

// 集合名
ChatModel.CL = BaseProjectModel.C('chat');

ChatModel.DB_STRUCTURE = {
	_pid: 'string|true',
	CHAT_ID: 'string|true',

	CHAT_USER_ID: 'string|false|comment=用户ID',
	CHAT_USER_NAME: 'string|false|comment=用户名称',
	
	CHAT_QUESTION: 'string|true|comment=用户问题',
	CHAT_ANSWER: 'string|true|comment=系统回答',
	
	CHAT_KNOWLEDGE_IDS: 'array|false|default=[]|comment=引用的知识ID',
	CHAT_VECTOR_SCORES: 'array|false|default=[]|comment=向量相似度得分',
	CHAT_RAW_PROMPT: 'string|false|comment=原始LLM提示',
	
	CHAT_SESSION_ID: 'string|false|comment=会话ID',
	CHAT_IP: 'string|false|comment=用户IP',
	
	CHAT_ADD_TIME: 'int|true',
	CHAT_EDIT_TIME: 'int|true',
};

// 字段前缀
ChatModel.FIELD_PREFIX = "CHAT_";

module.exports = ChatModel; 